package com.nd.service;

import com.nd.dao.*;
import com.nd.pojo.bean.*;
import com.nd.pojo.vo.DashboardVo;
import com.nd.pojo.vo.LoginAdminVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AdminServiceImpl implements AdminService{

    @Autowired
    AdminMapper adminMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    GoodsProductMapper productMapper;
    @Autowired
    PermissionMapper permissionMapper;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    JurisdictionMapper jurisdictionMapper;

    @Override
    public DashboardVo queryDashboardVo() {

        GoodsExample goodsExample = new GoodsExample();
        Long goodsTotal = goodsMapper.countByExample(goodsExample);

        UserExample userExample = new UserExample();
        Long userTotal = userMapper.countByExample(userExample);

        GoodsProductExample productExample = new GoodsProductExample();
        long productTotal = productMapper.countByExample(productExample);

        OrderExample orderExample = new OrderExample();
        long orderTotal = orderMapper.countByExample(orderExample);

        return new DashboardVo(goodsTotal,userTotal,productTotal,orderTotal);
    }

    @Override
    public LoginAdminVo getLoginAdminVo() {
        Subject subject = SecurityUtils.getSubject();
        Admin admin = (Admin) subject.getPrincipal();

        LoginAdminVo loginAdminVo = new LoginAdminVo();

        loginAdminVo.setName(admin.getUsername());
        List<String> roles = new ArrayList<>();
        List<String> perms = new ArrayList<>();
        List<String> permsPath = new ArrayList<>();
        Integer[] roleIds = admin.getRoleIds();
        for (Integer roleId : roleIds) {
            List<String> permsById = permissionMapper.selectPermsById(roleId);
            perms.addAll(permsById);
            Role role = roleMapper.selectByPrimaryKey(roleId);
            roles.add(role.getName());
        }

        for (String perm : perms) {
            if("*".equals(perm)){
                permsPath.add("*");
                break;
            }
            Jurisdiction jurisdiction = jurisdictionMapper.selectByPrimaryKey(perm);
            permsPath.add(jurisdiction.getApi());
        }
        loginAdminVo.setRoles(roles);
        loginAdminVo.setPerms(permsPath);
        loginAdminVo.setAvatar(admin.getAvatar());
        return loginAdminVo;
    }

}
